<template>
  <view class="order-content">
    <nav-bar ref="navBar" title="我的订单" />
    <scroll-tab
      :style="{ top: navbarHeight + 'px' }"
      class="scroll-tab"
      :tabData="tabData"
      @tabMsg="tabMsg"
    ></scroll-tab>
    <view v-if="orderData.list.length > 0" class="order-list">
      <view
        v-for="(curItem, curIndex) in orderData.list"
        :key="curIndex"
        class="li-box"
      >
        <view v-if="shopId" class="top-info">
          <view class="lef">
            <view class="title" style="font-size: 24rpx; margin-left: 0"
              >订单编号：{{ curItem.orderNo }}</view
            >
          </view>
          <view class="rig">{{ curItem.orderStatus }}</view>
        </view>
        <view v-else class="top-info">
          <view class="lef">
            <view class="logo"><xh-img :src="curItem.storeCover" /></view>
            <view class="title">{{ curItem.storeName }}</view>
          </view>
          <view class="rig">{{ curItem.orderStatus }}</view>
        </view>
        <view
          v-if="curItem.items.length === 1"
          @click="jumpOrderDetails(curIndex)"
          class="cen-info"
        >
          <view class="shop">
            <view class="img"><xh-img :src="curItem.items[0].coverImg" /></view>
            <view class="shopTxt">
              <view class="name">{{ curItem.items[0].title }}</view>
              <view v-if="curItem.items[0].skuInfo !== '[]'" class="spec">
                {{ JSON.parse(curItem.items[0].skuInfo) }}
              </view>
            </view>
          </view>
          <view class="num">
            <view class="money"
              >￥{{ $myTool.toFixedNum(curItem.items[0].price / 100) }}</view
            >
            <view class="txt">x{{ curItem.items[0].num }}</view>
          </view>
        </view>
        <view v-else @click="jumpOrderDetails(curIndex)" class="cen-info-more">
          <scroll-view class="scroll-view" scroll-x="true" scroll-left="0">
            <view
              v-for="(sItem, sIndex) in curItem.items"
              :key="sIndex"
              class="scroll-view-item"
              ><xh-img :src="sItem.coverImg"
            /></view>
          </scroll-view>
          <view class="num">{{ curItem.totalNum }} 件</view>
        </view>

        <view class="btm-info">
          <view class="lef">
            <view class="txt">
              {{
                curItem.orderStatus === "待支付" ||
                (curItem.orderStatus === "已取消" && curItem.refundAmt === 0)
                  ? "应付："
                  : curItem.refundAmt
                  ? "已退："
                  : "实付："
              }}
            </view>
            <view class="money">
              <span>￥</span>
              {{
                $myTool.toFixedNum(
                  (curItem.totalFee - curItem.allDiscountFee) / 100
                )
              }}
            </view>
          </view>
          <view v-if="curItem.orderStatus !== '进行中'" class="rig">
            <view v-if="curItem.orderStatus === '待付款'" class="time">{{
              curItem.endTime
            }}</view>
            <button
              v-if="
                curItem.orderStatus === '已取消' ||
                curItem.orderStatus === '已完成'
              "
              @click="handleAgain(curIndex)"
              class="againBtn"
              hover-class="hoverClass"
              :style="{ borderColor: themeColor, color: themeColor }"
            >
              再来一单
            </button>
            <button
              v-else
              @click="handlePay(curIndex)"
              class="payBtn"
              hover-class="hoverClass"
              :style="{ backgroundColor: themeColor }"
            >
              立即支付
            </button>
          </view>
        </view>
      </view>
    </view>
    <view v-else class="noData"
      ><list-empty
        iconUrl="https://hyyxboss.oss-cn-shenzhen.aliyuncs.com//img/pub/no_data.png"
        title="当前无订单"
    /></view>
    <cus-tabbar v-if="isShowTabbar" />
  </view>
</template>

<script>
import { mapState } from "vuex";
import scrollTab from "@/pages/sp-order/pages/store-order-list/components/scroll-tab";
import ListEmpty from "@/components/baseComponents/list-enpty/index.vue";
import { order_list } from "@/service/api/sp-order/index";
import { getShopDetail } from "@/service/api/sp-store/index";
export default {
  components: {
    scrollTab,
    ListEmpty,
  },
  computed: {
    ...mapState("sp-common/base", ["themeColor"]),
  },
  data() {
    return {
      isShowTabbar: false,

      tabData: [
        {
          name: "全部",
          value: "",
        },
        {
          name: "待付款",
          value: "WAITING",
        },
        {
          name: "进行中",
          value: "UNDERWAY",
        },
        {
          name: "已完成",
          value: "FINISH",
        },
        {
          name: "已取消",
          value: "CANCEL",
        },
      ],
      navbarHeight: "",

      // 查询条件
      conditions: {
        pageNum: 1,
        pageSize: 10,
        status: "", //WAITING: 待支付, UNDERWAY: 进行中, FINISH: 已完成, CANCEL:已取消
        shopId: "",
      },
      // 订单
      orderData: {
        list: [],
        hasNextPage: "",
      },
      shopInfo: "",
      shopId: "",
      timeId:''
    };
  },
  mounted() {
    this.initData();
    this.navbarHeight =
      this.$refs.navBar.navbarHeight + this.$refs.navBar.statusBarHeight;
  },
  methods: {
    // 代替onShow 生命周期 tabbar 页面独有
    onActive() {
      console.log("Order page onActive");
    },
    // 代替onLoad 生命周期 tabbar 页面独有
    onMount() {
      console.log("Order page onMount");
    },
    // tab
    tabMsg(val) {
      this.conditions.status = val.value;
      this.order_listFun(true);
    },

    // 初始化
    initData() {
      let { shopId, isShowTabbar } = this.$Route.query;
      this.isShowTabbar = isShowTabbar;
      this.shopId = shopId;
      this.conditions.pubShopId = shopId;
      this.order_listFun(true);
    },
    // 获取订单列表
    order_listFun(empty) {
      if (empty) {
        this.conditions.pageNum = 1;
        this.orderData.list = [];
      }
      order_list(this.conditions).then((res) => {
        console.log("获取订单列表", res);
        res.list.forEach((el) => {
          el.items[0].skuInfo = JSON.parse(JSON.stringify(el.items[0].skuInfo)); //html中，当只有一个商品才显示规格
          this.orderData.list.push(el);
        });
        this.orderData.hasNextPage = res.hasNextPage;
        this.timeId =  setInterval(() => {
          this.countdownFun();
        }, 1000);
        uni.stopPullDownRefresh();
      });
    },
    // 倒计时
    countdownFun() {
      // 添加结束时间
      for (let t = 0; t < this.orderData.list.length; t++) {
        let endTime = this.orderData.list[t].lastPayTime; //结束时间

        let date = new Date(endTime);
        let times =
          date.getFullYear() +
          "/" +
          (date.getMonth() + 1) +
          "/" +
          date.getDate() +
          " " +
          date.getHours() +
          ":" +
          date.getMinutes() +
          ":" +
          date.getSeconds();
        if (date.getMinutes() < 10) {
          date = "0" + date.getMinutes(); //补齐
        }

        let nowtime = new Date(); //定义当前时间
        let targetTime = new Date(times); //目标时间
        let spantime = targetTime - nowtime; //目标时间减去当前时间，得到距离时间
        if (spantime <= 0) {
          this.orderData.list[t].endTime = "已失效";
          return;
        }

        //还没到时间,计算出时分秒
        let hour = Math.floor(spantime / (1000 * 60 * 60)); //时
        spantime -= hour * 60 * 60 * 1000; //去掉总毫秒差中计算出的时间差
        let minute = Math.floor(spantime / (1000 * 60)); //分
        spantime -= minute * 60 * 1000;

        let second = Math.floor(spantime / 1000); //秒
        spantime -= second * 1000;

        //不足十位补0
        minute < 10 ? (minute = "0" + minute) : null;
        second < 10 ? (second = "0" + second) : null;
        this.$set(
          this.orderData.list[t],
          "endTime",
          "剩余" + minute + ":" + second
        );
      }
    },

    //去支付
    async handlePay(curIndex) {
      let { orderNo, pubShopId } = this.orderData.list[curIndex];
      let { storeNo } = await getShopDetail({ id: pubShopId });
      this.$pay({ xhOrderNo: orderNo, storeNo }).then((res) => {
        console.log("收银台", res);
        if (res.code === 0) {
          uni.showToast({
            title: "支付成功",
            icon: "none",
          });
          setTimeout((res) => {
            this.initData();
          }, 2000);
        }
      });
    },
    //再来一单
    handleAgain(curIndex) {
      this.$myTool.jumpPage("shopIndex", {
        shopId: this.orderData.list[curIndex].pubShopId,
      });
    },
    // 触底
    onReachBottom() {
      if (this.orderData.hasNextPage) {
        this.conditions.pageNum++;
        this.order_listFun();
      }
    },
    //跳转详情
    jumpOrderDetails(curIndex) {
      uni.navigateTo({
        url: `pages/sp-order/pages/store-order-details/index`,
        events: {
          orderStatus: (res) => {
            this.initData();
          },
        },
        success: (res) => {
          res.eventChannel.emit("orderList", {
            data: this.orderData.list[curIndex],
          });
        },
      });
    },
    onPullDownRefresh() {
      console.log("下拉刷新");
      this.order_listFun(true);
    },
    beforeDestroy() {
      clearInterval(this.timeId)
    },
  },
};
</script>
<style>
page {
  background-color: #f7f7f7;
}
</style>
<style lang="scss" scoped>
.order-content {
  padding-bottom: 200rpx;

  .scroll-tab {
    position: fixed;
    left: 0;
    z-index: 10;
    width: 100%;
    height: 115rpx;
    overflow: hidden;
    background-color: #f7f7f7;
    display: flex;
    align-items: center;
  }

  .order-list {
    flex: 1;
    margin-top: 115rpx;
    padding: 20rpx;
    box-sizing: border-box;

    .li-box {
      background-color: white;
      border-radius: 10rpx;
      padding: 24rpx;
      box-sizing: border-box;
      margin-bottom: 24rpx;

      .top-info {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .lef {
          display: flex;
          align-items: center;
          flex: 4;

          .logo {
            width: 67rpx;
            height: 67rpx;
            border-radius: 50%;
            overflow: hidden;
            float: left;
          }

          .title {
            float: left;
            font-size: 32rpx;
            font-weight: bold;
            color: #181818;
            margin-left: 16rpx;
          }
        }

        .rig {
          flex: 1;
          width: 100%;
          text-align: right;
          font-size: 27rpx;
          font-weight: 500;
        }
      }

      .cen-info-more {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 24rpx 0;
        padding: 24rpx 0;
        border-top: 1rpx solid #ececec;
        border-bottom: 1rpx solid #ececec;

        .scroll-view {
          white-space: nowrap;
          flex: 6;
          overflow: hidden;

          .scroll-view-item {
            width: 150rpx;
            height: 150rpx;
            overflow: hidden;
            margin-left: 16rpx;
            display: inline-block;
          }
        }

        .num {
          flex: 1;
          text-align: right;
          font-size: 27rpx;
          font-weight: 500;
          color: #888888;
        }
      }

      .cen-info {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 24rpx 0 16rpx 0;
        padding: 24rpx 0;
        border-top: 1rpx solid #ececec;
        border-bottom: 1rpx solid #ececec;

        .shop {
          display: flex;
          align-items: center;

          .img {
            width: 150rpx;
            height: 150rpx;
            overflow: hidden;
            margin-right: 16rpx;
            float: left;
          }

          .shopTxt {
            float: left;

            .name {
              font-size: 29rpx;
              font-weight: bold;
              color: #181818;
            }

            .spec {
              margin-top: 21rpx;
              padding: 5rpx 14rpx;
              color: #888888;
              opacity: 0.8;
              font-size: 27rpx;
              border: 1px solid #b4b4b4;
              opacity: 0.8;
              border-radius: 8rpx;
              width: fit-content;
            }
          }
        }

        .num {
          font-size: 29rpx;
          font-weight: 500;

          .money {
            color: #f05357;
          }

          .txt {
            color: #888888;
            text-align: right;
          }
        }
      }

      .btm-info {
        width: 100%;
        display: flex;
        justify-content: space-between;

        .lef {
          font-size: 29rpx;
          display: flex;
          align-items: center;

          .txt {
            float: left;
            color: #181818;
            font-weight: bold;
          }

          .money {
            float: left;
            color: #f26a6e;

            span {
              font-size: 24rpx;
            }
          }
        }

        .rig {
          display: flex;
          align-items: center;

          .time {
            font-size: 27rpx;
            font-weight: 500;
            color: #888888;
            float: right;
            margin-right: 13rpx;
          }

          .payBtn,
          .againBtn {
            width: 170rpx;
            height: 56rpx;
            border-radius: 28rpx;
            font-size: 29rpx;
            font-weight: 500;
            color: #ffffff;
            text-align: center;
            line-height: 56rpx;
            float: right;
            padding: 0;
            border: 1px solid #ffffff;
            background-color: white;
          }

          button::after {
            border: none;
          }

          .hoverClass {
            opacity: 0.5;
          }
        }
      }
    }
  }

  .noData {
    position: fixed;
    top: 50%;
    left: 0;
    width: 100%;
    text-align: center;
    color: #ccc;
  }
}
</style>
